package com.dms.shanshan.core;

import com.dms.shanshan.annotion.ExcelStrategyIdentifier;
import com.dms.shanshan.annotion.StrategyMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ExcelStrategyFactory {
    private final Map<Class<?>, Object> strategyInstances = new HashMap<>();
    public final Map<String, Method> MethodMap = new HashMap<>();

    public ExcelStrategyFactory(String basePackage) {
        scanBean(basePackage);
        scanMethod();
    }

    private void scanBean(String basePackage) {
        String path = basePackage.replace(".", "/");
        URL url = this.getClass().getClassLoader().getResource(path);
        if (url == null) return;

        File dir = new File(url.getFile());
        for (File file : dir.listFiles()) {
            try {
                if (file.isDirectory()) {
                    scanBean(basePackage + "." + file.getName());
                } else if (file.getName().endsWith(".class")) {
                    String className = basePackage + "."
                            + file.getName().replace(".class", "");
                    Class<?> clazz = Class.forName(className);
                    if (clazz.isAnnotationPresent(ExcelStrategyIdentifier.class)) {
                        System.out.println("发现策略类: " + clazz.getName());
                        Object instance = clazz.getDeclaredConstructor().newInstance();
                        strategyInstances.put(clazz, instance);
                    }
                }
            } catch (Exception e) {
                System.err.println("加载类失败: " + file.getName());
            }
        }
    }

    private void scanMethod() {
        strategyInstances.forEach((clazz, instance) -> {
            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(StrategyMethod.class)) {
                    StrategyMethod annotation = method.getAnnotation(StrategyMethod.class);
                    System.out.println("注册方法: " + annotation + " -> " + method.getName());

                    MethodMap.put(annotation.value(), method);
                }
            }
        });
    }

    public Object handle(String methodName, Object... args) {
        Method method = MethodMap.get(methodName);
        if (method == null) throw new IllegalArgumentException("方法不存在");

        try {
            // 查找匹配的实例
            Object instance = strategyInstances.get(method.getDeclaringClass());
            return method.invoke(instance, args);
        } catch (Exception e) {
            throw new RuntimeException("方法执行失败", e);
        }
    }
// 测试代码
}